<template>
  <div class="wrapper">
    <dx-header-bar title="客户信息"></dx-header-bar>
    <md-tab-bar v-model="customerType" :items="ctmTypes" @change="changeType"/>
    <dx-search-bar placeholder="搜索" component="customer" @click.native="showSearchPopup"/>
    <dx-search-customer ref="searchPopup" :default-value="searchDefaultValue" @on-search="search">

    </dx-search-customer>
    <md-scroll-view class="scroll-view"
                    ref="scrollView"
                    :scrolling-x="false"
                    @refreshing="$_onRefresh"
                    @endReached="$_onEndReached">
      <md-scroll-view-refresh slot="refresh"
                              slot-scope="{ scrollTop, isRefreshActive, isRefreshing }"
                              refreshing-text="加载中…"
                              :scroll-top="scrollTop"
                              :is-refreshing="isRefreshing"
                              :is-refresh-active="isRefreshActive"/>
      <md-scroll-view-more slot="more"
                           :is-finished="isFinished"
                           :finished-text="finishedText"/>
      <md-field class="scroll-view-item"
                v-for="(item, index) in dataList"
                :key="index">
        <div slot="header" class="view-item-header">
          <span class="index">{{index+1}}.</span>
          <span class="title">{{item.ZH_LABEL}}</span>
          <span class="follow iconfont icon-star-fill"
                :class="{followed: item.IS_ATTENTION === '是'}"
                @click="toggleAttention(item)">
          </span>
        </div>
        <template slot="footer">
          <md-button @click="openService(item)"
                     type="primary" size="small"
                     inline plain>客户服务
          </md-button>
          <md-button @click="openAlarm(item)"
                     type="primary" size="small"
                     inline plain>告警
          </md-button>
          <md-button @click="openOrder(item)"
                     type="primary" size="small"
                     inline plain>工单
          </md-button>
          <md-button @click="openBusi(item)"
                     type="primary" size="small"
                     inline plain>业务
          </md-button>
        </template>
        <md-detail-item title="客户编号：">
          <div class="detail-item-content">{{item.CUSTOMER_CODE}}</div>
        </md-detail-item>
        <md-detail-item title="客户服务等级：">
          <div class="detail-item-content">{{item.SERVICE_LEVEL | levelFilter}}</div>
        </md-detail-item>
        <md-detail-item title="客户级别：">
          <div class="detail-item-content">{{item.CUSTOMER_GRADE | gradeFilter}}</div>
        </md-detail-item>
        <md-detail-item title="客户地市：">
          <div class="detail-item-content">{{item.CITY_ID}}</div>
        </md-detail-item>
        <md-detail-item title="客户经理：">
          <div class="detail-item-content">
            {{item.MARKETING_MANAGER}}&nbsp;
            <a :href="'tel:'+item.MARKETING_PHONE">{{item.MARKETING_PHONE}}</a>
          </div>
        </md-detail-item>
        <md-detail-item title="技术经理：">
          <div class="detail-item-content">
            {{item.TECH_MANAGER}}&nbsp;
            <a :href="'tel:'+item.TECH_MANAGER_PHONE">{{item.TECH_MANAGER_PHONE}}</a>
          </div>
        </md-detail-item>
        <md-detail-item title="客户联系人：">
          <div class="detail-item-content">
            {{item.CUSTOMER_CONTACT}}&nbsp;
            <a :href="'tel:'+item.CUSTOMER_PHONE">{{item.CUSTOMER_PHONE}}</a>
          </div>
        </md-detail-item>
        <md-detail-item title="客户地址：">
          <div class="detail-item-content">{{item.CUSTOMER_ADD}}</div>
        </md-detail-item>
      </md-field>
    </md-scroll-view>
  </div>
</template>

<script type="text/ecmascript-6">
import { mapState } from 'vuex';
import {
  // Dialog,
  Toast,
  ScrollView,
  ScrollViewRefresh,
  ScrollViewMore,
  TabBar,
  Field,
  DetailItem,
  Button
} from 'mand-mobile';
import { DxHeaderBar, DxSearchBar, DxSearchCustomer } from '@/components';
import customerFilter from '@/mixins/customerFilter';
import { getCustomerList, updateAttentionCustomer } from '@/api/resource';

export default {
  components: {
    DxHeaderBar,
    DxSearchBar,
    DxSearchCustomer,
    [ScrollView.name]: ScrollView,
    [ScrollViewRefresh.name]: ScrollViewRefresh,
    [ScrollViewMore.name]: ScrollViewMore,
    [TabBar.name]: TabBar,
    [Field.name]: Field,
    [DetailItem.name]: DetailItem,
    [Button.name]: Button
  },
  mixins: [customerFilter],
  data() {
    return {
      customerType: '',
      params: {
        page: 1,
        limit: 10
      },
      dataList: [],
      // ScrollViewMore
      isFinished: false,
      searchDefaultValue: '',
      timestamp: ''
    };
  },
  computed: {
    ...mapState({
      // tabBar
      ctmTypes: state => state.library.ctmTypes
    }),
    finishedText() {
      return this.dataList.length ? '已全部加载' : '没有数据';
    }
  },
  created() {
    this.init();
  },
  activated() {
    const timestamp = Number(this.$route.query.timestamp);
    if (this.timestamp !== timestamp) {
      this.timestamp = timestamp;
      this.init();
    }
  },
  deactivated() {
    this.$refs.searchPopup.reset();
  },
  methods: {
    init() {
      this.params = {
        type: '',
        page: 1,
        limit: 10
      };
      this.customerType = '';
      const { customerCode, customerName } = this.$route.query;
      this.searchDefaultValue = customerCode ? `&customerCode=${customerCode}` : '';
      this.searchDefaultValue += customerName ? `&customerName=${customerName}` : '';
      this.params.customerCode = customerCode || '';
      this.params.customerName = customerName || '';
      this.changeType(this.ctmTypes[0]);
    },
    showSearchPopup() {
      this.$refs.searchPopup.showPopup();
    },
    search(form) {
      this.params = Object.assign(this.params, form);
      this.isFinished = false;
      this.params.page = 1;
      // 搜索时触发下拉刷新增加交互动画，用于告知用户数据加载状态
      this.$refs.scrollView.triggerRefresh();
    },
    $_onRefresh() {
      this.isFinished = false;
      this.params.page = 1;
      this.loadData('refresh');
    },
    $_onEndReached() {
      if (this.isFinished) return;
      this.params.page += 1;
      this.loadData();
    },
    /**
     * @param data 列表数据
     * @param type 加载数据类型，下拉刷新或者上拉加载
     * @param isFinished Boolean 数据是否加载完毕
     */
    $_onFinished(data, type, isFinished) {
      this.isFinished = isFinished;
      if (type === 'refresh') {
        this.dataList = data;
        this.$refs.scrollView.finishRefresh();
      } else {
        this.dataList = this.dataList.concat(data);
        this.$refs.scrollView.finishLoadMore();
      }
    },
    /**
     * @param type 加载数据类型，下拉刷新或者上拉加载
     */
    loadData(type) {
      getCustomerList(this.params).then(result => {
        const { count, datas } = result.data;
        const { page, limit } = this.params;
        const data = datas instanceof Array && datas.length ? datas : [];
        this.$_onFinished(data, type, page * limit >= count);
      }).catch(() => {
        this.$_onFinished([], type, true);
      });
    },
    changeType(item) {
      if (!this.customerType) {
        this.customerType = item.name;
      }
      this.params.type = item.name;
      this.$nextTick(() => {
        this.$refs.scrollView.scrollTo(0, 0);
        this.$refs.scrollView.triggerRefresh();
      });
    },
    // toggleAttention(name, id, isAttention) {
    //   Dialog.confirm({
    //     title: '确认',
    //     content: `${isAttention ? '取消' : '添加'}关注${name}？`,
    //     confirmText: '确定',
    //     onConfirm: () => {
    //       this.updateAttention(id, isAttention ? '否' : '是');
    //     }
    //   });
    // },
    toggleAttention(item) {
      const payload = {};
      const isAttention = item.IS_ATTENTION === '是';
      if (isAttention) {
        payload.update_type = 'delete';
        payload.id = item.ID;
      } else {
        payload.update_type = 'insert';
        payload.customerCode = item.CUSTOMER_CODE;
      }
      updateAttentionCustomer(payload).then(result => {
        if (result.success) {
          Toast.succeed(`已${isAttention ? '取消' : '添加'}关注`);
          this.$refs.scrollView.triggerRefresh();
        } else {
          Toast.succeed('失败!');
        }
      }).catch(() => {
        Toast.succeed('失败!');
      });
    },
    openService(data) {
      this.$router.push({
        name: 'service',
        query: {
          customerName: data.ZH_LABEL,
          customerCode: data.CUSTOMER_CODE
        }
      });
    },
    openAlarm(item) {
      this.$router.push({
        name: 'alarm',
        query: {
          customerCode: item.CUSTOMER_CODE
        }
      });
    },
    openOrder(item) {
      this.$router.push({
        name: 'statisticsOrder',
        query: {
          customerCode: item.CUSTOMER_CODE
        }
      });
    },
    openBusi(item) {
      this.$router.push({
        name: 'statisticsBusiness',
        query: {
          customerCode: item.CUSTOMER_CODE
        }
      });
    }
  }
};
</script>

<style lang="stylus" scoped>
  .wrapper
    position : relative
    display : flex
    flex-direction : column
    height : 100%

  .scroll-view
    flex : 1

  .scroll-view-item
    margin-bottom : 20px
    padding : 20px

    &:last-of-type
      margin-bottom : 0

    .md-button
      float : right
      margin-left : 8px
      padding : 0 8px
      height : 48px
      font-size : 24px

  .view-item-header
    color : theme-color
    font-size : 32px
    font-weight : bold

    .index
      margin-right : 20px
      color : #333

    .follow
      margin-left : 20px
      vertical-align : top
      display : inline-block
      width : 34px
      height : 34px
      font-size : 34px
      color : #ccc

      &.followed
        color : #ffa500

  .detail-item-content
    flex : 1
</style>
